import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/ToastUtil.dart';
import 'package:magic_car/util/colors.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:magic_car/main.dart';
import 'package:toast/toast.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'dart:async';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:typed_data';
import 'package:permission_handler/permission_handler.dart';

class CodePage extends StatefulWidget {
  CodePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<CodePage> {
  Map userinfo = new Map();
  File _image;
  String avatar = '';
  String CodeUrl = "";
  bool nohalf = false;
  String halfalerstr="";

  @override
  void initState() {
    super.initState();
    loaduserinfo();
  }

  loaduserinfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid');
    String role = pref.getString('role');
    // String API = HttpHelper.API_Qrcode;
    String API = HttpHelper.API_Qrcodever;
    if (role != "1") {
      API = HttpHelper.API_QudaoCode;
      map["type"] = '3';
    }

    HttpHelper.post(API, (data) async {
      if (data != null) {
        print(data);
         Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          if (data["info"]['nohalf'] != "") {
            setState(() {
              nohalf = true;
              halfalerstr = data["info"]['nohalf'];
            });
           // Toast.show(data["info"]['nohalf'], context);
          }
          setState(() {
            avatar = data["info"]["url"];
            CodeUrl = data["info"]["codeurl"];
          });
        } else {
         // Toast.show(data["msg"], context);
        }
      }
    }, params: map);
  }

  _saveImg() async {
    // 检查并请求权限
    //   PermissionStatus status = await PermissionHandler()
    //       .checkPermissionStatus(PermissionGroup.storage);
    //   if (PermissionStatus.granted != status) {
    //     PermissionHandler().requestPermissions(<PermissionGroup>[
    //       PermissionGroup.storage,
    //     ]);
    //   }
    //  // print(qrcodeData);
    //   var response = await Dio()
    //       .get(avatar, options: Options(responseType: ResponseType.bytes));
    //       // final result =
    //       // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
    //   final result =
    //       await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
    //   print('result:$result');
    //   if(result!=null){
    //    Toast.show('保存成功', context);
    //   }else{
    //     Toast.show('保存失败', context);
    //   }

    if (Platform.isAndroid) {
      if (await Permission.storage.request().isGranted) {
        var response = await Dio()
            .get(avatar, options: Options(responseType: ResponseType.bytes));
        // final result =
        // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
        final result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(response.data));
        print('result:$result');
        if (result != null) {
          Toast.show('保存成功', context);
        } else {
          Toast.show('保存失败', context);
        }
      }
      // 检查并请求权限
      // PermissionStatus status = await PermissionHandler()
      //     .checkPermissionStatus(PermissionGroup.storage);
      // if (PermissionStatus.granted != status) {
      //   PermissionHandler().requestPermissions(<PermissionGroup>[
      //     PermissionGroup.storage,
      //   ]);
      // } else {
      //   var response = await Dio()
      //       .get(avatar, options: Options(responseType: ResponseType.bytes));
      //   // final result =
      //   // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
      //   final result = await ImageGallerySaver.saveImage(
      //       Uint8List.fromList(response.data));
      //   print('result:$result');
      //   if (result != null) {
      //   } else {}
      // }
    } else {
      if (await Permission.photos.request().isGranted) {
        var response = await Dio()
            .get(avatar, options: Options(responseType: ResponseType.bytes));
        // final result =
        // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
        final result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(response.data));
        print('result:$result');
        if (result != null) {
          Toast.show('保存成功', context);
        } else {
          Toast.show('保存失败', context);
        }
      }
    }

    // if(Utils.isEmpty(result)){
    //   print('保存失败');
    // }else{
    //   print('保存成功');
    // }
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          titleSpacing: 0,
            title: new Text(
              '二维码',
              style: TextStyle(color: Colors.white,fontSize: Config.title_size),
            ),
            iconTheme: new IconThemeData(color: Colors.white),
            backgroundColor: Colours.app_main,
            elevation: 0),
        body: Container(
            color: Color.fromRGBO(239, 239, 239, 1),
            child: new ListView(children: <Widget>[
              new Column(children: <Widget>[
                GestureDetector(
                    onTap: () {
                      showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return new AlertDialog(
                            title:Center(child: new Text('我的二维码',style: TextStyle(fontSize: 16),)),
                            content: new SingleChildScrollView(
                                child: new Image.network(
                              CodeUrl,
                              width: 300,
                              height: 300,
                              fit: BoxFit.fitHeight,
                            )),
                            // actions: <Widget>[
                            //   new FlatButton(
                            //     child: new Text('确定'),
                            //     onPressed: () {
                            //       Navigator.of(context).pop();
                            //     },
                            //   ),
                            // ],
                          );
                        },
                      );
                    },
                    child:avatar==""?Container(height: 0,): new Image.network(
                      avatar,
                      width: double.infinity,
                      height: 550,
                      fit: BoxFit.fitHeight,
                    )
                    ),
                    nohalf?new Container(
                      child:
                      Padding(padding: new EdgeInsets.all(19),child:
                      Text(halfalerstr,style: TextStyle(color:Colors.red,fontSize:13),))
                    ):new Container(height: 0),
                new Container(
                  height: 50,
                  decoration: new BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                      border: new Border.all(width: 0, color: Colors.white)),
                  child: new Column(children: <Widget>[
                    Container(
                      padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                      height: 50,
                      decoration: new BoxDecoration(
                          // color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(5)),
                          border:
                              new Border.all(width: 0, color: Colors.white)),
                      child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: new FlatButton(
                            child: Text(
                              '保存图片',
                              style: TextStyle(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  fontSize: 16),
                            ),
                            color: Colours.app_main,
                            textColor: Colors.black,
                            onPressed: () async {
                              _saveImg();
                            },
                          )),
                    )
                    // Padding(
                    //   padding: new EdgeInsets.fromLTRB(0, 10, 0, 10),
                    // child:
                    // Center(
                    //   child:new Text("扫一扫，了解我的信息")
                    // )),
                    //child:new Text("11111")
                  ]),
                )
                //)
              ])
              // Container(
              //     height: 600,
              //     child: Stack(children: <Widget>[
              //       Positioned(
              //         top: 0,
              //         left: 0,
              //         right: 0,

              //         // child:
              //         // Center(
              //         child: new Container(
              //             color: Color.fromRGBO(25, 168, 249, 1),
              //             height: 150,
              //             // width: double.infinity,
              //             child: Text('')),
              //       ),
              //       Positioned(
              //         top: 80.0,
              //         left: 20,
              //         right: 20,
              //         child: new Container(

              //           height: 600,
              //           decoration: new BoxDecoration(
              //               color: Colors.white,
              //               borderRadius: BorderRadius.all(Radius.circular(5)),
              //               border:
              //                   new Border.all(width: 0, color: Colors.white)),
              //           child: new Column(children: <Widget>[
              //             new Image.network(
              //               avatar,
              //               width: double.infinity,
              //               height: 550,
              //               fit: BoxFit.fitHeight,
              //             ),
              //             // Padding(
              //             //   padding: new EdgeInsets.fromLTRB(0, 10, 0, 10),
              //             // child:
              //             // Center(
              //             //   child:new Text("扫一扫，了解我的信息")
              //             // )),
              //             //child:new Text("11111")
              //           ]),
              //         ),
              //       ),
              //       // Positioned(
              //       //     bottom: 0.0,
              //       //     left: 20,
              //       //     right: 20,
              //       //     child:
              //           new Container(
              //             height: 50,
              //             decoration: new BoxDecoration(
              //                 color: Colors.white,
              //                 borderRadius:
              //                     BorderRadius.all(Radius.circular(5)),
              //                 border: new Border.all(
              //                     width: 0, color: Colors.white)),
              //             child: new Column(children: <Widget>[
              //               Container(
              //                 padding: new EdgeInsets.fromLTRB(20, 0, 20, 0),
              //                 height: 50,
              //                 decoration: new BoxDecoration(
              //                     // color: Colors.white,
              //                     borderRadius:
              //                         BorderRadius.all(Radius.circular(5)),
              //                     border: new Border.all(
              //                         width: 0, color: Colors.white)),
              //                 child: SizedBox(
              //                     width: double.infinity,
              //                     height: 50,
              //                     child: new FlatButton(
              //                       child: Text(
              //                         '保存图片',
              //                         style: TextStyle(
              //                             color:
              //                                 Color.fromRGBO(102, 102, 102, 1),
              //                             fontSize: 16),
              //                       ),
              //                       color: Colors.white,
              //                       textColor: Colors.black,
              //                       onPressed: () async {
              //                        _saveImg();
              //                       },
              //                     )),
              //               )
              //               // Padding(
              //               //   padding: new EdgeInsets.fromLTRB(0, 10, 0, 10),
              //               // child:
              //               // Center(
              //               //   child:new Text("扫一扫，了解我的信息")
              //               // )),
              //               //child:new Text("11111")
              //             ]),
              //           )
              //           //)
              //     ])),
            ])));
  }
}
